package com.dc.system.serviceImpl;

import com.dc.base.exception.BusinessException;
import com.dc.base.utils.MD5Util;
import com.dc.base.utils.RequestUtil;
import com.dc.common.constants.ConstantsCommon;
import com.dc.common.model.BaseModel;
import com.dc.system.dto.SysUserDTO;
import com.dc.system.mapper.LogMapper;
import com.dc.system.mapper.UserMapper;
import com.dc.system.model.SysLoginlog;
import com.dc.system.model.SysUser;
import com.dc.system.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogMapper loginlogMapper;

    @Override
    public BaseModel login(BaseModel baseModel, SysUser user, HttpServletRequest request) throws Exception {
        //验证数据验证数据
        if (user.getAccount() == null || "".equals(user.getAccount().trim())) {
            throw new BusinessException(-101, "账号不能为空");
        }
        if (user.getPassword() == null || "".equals(user.getPassword().trim())) {
            throw new BusinessException(-102, "密码不能为空");
        }
        //查询
        user.setPassword(MD5Util.md5(user.getPassword()));
        SysUser userSelect = userMapper.getUserByAccountAndPwd(user);
        // 设置登录日志信息
        SysLoginlog sysLoginlog = new SysLoginlog();
        sysLoginlog.setUserAccount(user.getAccount());
        //sysLoginlog.setUserPassword(user.getPassword());
        sysLoginlog.setLoginDate(new Date());
        sysLoginlog.setRequestIp(RequestUtil.getInstance().getIpAddress(request));
        sysLoginlog.setSessionId(request.getSession().getId());
        sysLoginlog.setType(0);
        //判断
        if (userSelect != null) {
            userSelect.setPassword("");
            baseModel.setMessage("登录成功");
            baseModel.setData(userSelect);
            //用户信息放入session
            request.getSession().setAttribute(ConstantsCommon.LOGIN_INFO, userSelect);
            //剩余登录日志信息
            sysLoginlog.setUserId(userSelect.getUserId());
            sysLoginlog.setUserName(userSelect.getName());
            sysLoginlog.setState(1);
            loginlogMapper.insertLoginlog(sysLoginlog);
        } else {
            sysLoginlog.setState(0);
            loginlogMapper.insertLoginlog(sysLoginlog);
            throw new BusinessException(-103, "账号或者密码错误");
        }
        return baseModel;
    }

    @Override
    public BaseModel loginOut(BaseModel baseModel, HttpServletRequest request) throws Exception {
        request.getSession().setAttribute(ConstantsCommon.LOGIN_INFO, null);
        baseModel.setMessage("安全退出成功");
        return baseModel;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseModel addUser(BaseModel baseModel, SysUser user, HttpServletRequest request, int deptId, int roleId) throws Exception {
        //验证数据
        if (user.getAccount() == null || "".equals(user.getAccount().trim())) {
            throw new BusinessException(-101, "用户账号不能为空");
        }
        if (user.getName() == null || "".equals(user.getName().trim())) {
            throw new BusinessException(-103, "用户姓名不能为空");
        }
        if (deptId <= 0) {
            throw new BusinessException(-104, "请选择部门");
        }
        if (roleId <= 0) {
            throw new BusinessException(-105, "请选择角色");
        }
        if (user.getPassword() != null && !"".equals(user.getPassword()) && (user.getPassword().trim().length() < 6 || user.getPassword().trim().length() > 16)) {
            throw new BusinessException(-106, "请输入6-16位的密码");
        }
        if (user.getPassword() == null || "".equals(user.getPassword().trim())) {
            user.setPassword(MD5Util.md5("111111"));
        } else {
            user.setPassword(MD5Util.md5(user.getPassword()));
        }
        //创建人信息
        SysUser userNow = (SysUser) request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        user.setCreateUserId(userNow.getUserId());
        user.setCreateUserName(userNow.getName());
        user.setCreateTime(new Date());
        //添加用户
        int lines = userMapper.addUser(user);
        if (lines <= 0) {
            throw new BusinessException(-107, "新增用户失败");
        }
        //此处后期可加查询对应的部门和角色是否存在

        //用户部门以及角色关联
        Map map = new HashMap();
        map.put("fkUserId", user.getUserId());
        map.put("fkDeptId", deptId);
        map.put("fkRoleId", roleId);
        //添加关联
        int lines2 = userMapper.addUserDept(map);
        int lines3 = userMapper.addUserRole(map);
        if (lines2 <= 0 || lines3 <= 0) {
            throw new BusinessException(-108, "新增用户失败");
        }
        baseModel.setMessage("新增成功");
        return baseModel;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseModel updateUser(BaseModel baseModel, SysUser user, HttpServletRequest request, int deptId, int roleId) throws Exception {
        //验证数据
        if (user.getUserId() <= 0) {
            throw new BusinessException(-101, "用户唯一标识获取失败");
        }
        if (user.getAccount() == null || "".equals(user.getAccount().trim())) {
            throw new BusinessException(-102, "用户账号不能为空");
        }
        if (user.getName() == null || "".equals(user.getName().trim())) {
            throw new BusinessException(-104, "用户姓名不能为空");
        }
        if (deptId <= 0) {
            throw new BusinessException(-105, "请选择部门");
        }
        if (roleId <= 0) {
            throw new BusinessException(-106, "请选择角色");
        }
        //根据id查询用户
        SysUserDTO userById = userMapper.getUserById(user.getUserId());
        if (userById.getVersion() != user.getVersion()) {
            throw new BusinessException(-107, "修改失败，数据版本不一致");
        }
        //设置修改信息
        userById.setAccount(user.getAccount());
        userById.setName(user.getName());
        userById.setState(user.getState());
        if (user.getPassword() != null && !"".equals(user.getPassword()) && (user.getPassword().trim().length() < 6 || user.getPassword().trim().length() > 16)) {
            throw new BusinessException(-108, "请输入6-16位的密码");
        }
        if (user.getPassword() != null && !"".equals(user.getPassword().trim())) {
            userById.setPassword(MD5Util.md5(user.getPassword()));
        }
        //修改人信息
        SysUser userNow = (SysUser) request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        userById.setUpdateUserId(userNow.getUserId());
        userById.setUpdateUserName(userNow.getName());
        userById.setUpdateTime(new Date());
        //修改用户
        int lines = userMapper.updateUser(userById);
        if (lines <= 0) {
            throw new BusinessException(-109, "修改用户失败");
        }
        //此处后期可加查询对应的部门和角色是否存在

        //用户部门以及角色关联
        Map map = new HashMap();
        map.put("fkUserId", user.getUserId());
        map.put("fkDeptId", deptId);
        map.put("fkRoleId", roleId);
        //删除之前的关联
        userMapper.delUserDept(user.getUserId());
        userMapper.delUserRole(user.getUserId());
        //添加关联
        int lines2 = userMapper.addUserDept(map);
        int lines3 = userMapper.addUserRole(map);
        if (lines2 <= 0 || lines3 <= 0) {
            throw new BusinessException(-110, "修改用户失败");
        }
        baseModel.setMessage("修改成功");
        return baseModel;
    }

    @Override
    public BaseModel getUserById(BaseModel baseModel, SysUser user) throws Exception {
        //验证数据
        if (user.getUserId() <= 0) {
            throw new BusinessException(-101, "用户唯一标识获取失败");
        }
        //根据id查询用户
        SysUserDTO userById = userMapper.getUserById(user.getUserId());
        if (userById == null) {
            throw new BusinessException(-102, "未查询到对应的用户信息");
        } else {
            userById.setPassword("");
            baseModel.setData(userById);
        }
        return baseModel;
    }

    @Override
    public BaseModel delUser(BaseModel baseModel, SysUser user, HttpServletRequest request) throws Exception {
        //验证数据
        if (user.getUserId() <= 0) {
            throw new BusinessException(-101, "用户唯一标识获取失败");
        }
        //根据id查询用户
        SysUserDTO userById = userMapper.getUserById(user.getUserId());
        if (userById == null) {
            throw new BusinessException(-102, "该用户不存在,删除失败");
        }
        //修改人信息
        SysUser userNow = (SysUser) request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        userById.setUpdateUserId(userNow.getUserId());
        userById.setUpdateUserName(userNow.getName());
        userById.setUpdateTime(new Date());
        //修改删除标识
        userById.setIsDeleted(0);
        //部门删除
        int lines = userMapper.updateUser(userById);
        if (lines <= 0) {
            throw new BusinessException(-103, "删除用户失败");
        } else {
            baseModel.setMessage("删除成功");
        }

        return baseModel;
    }

    @Override
    public BaseModel getUsers(BaseModel baseModel, SysUser user) throws Exception {
        //验证数据，处理数据
        Map map = new HashMap();
        if (baseModel.getKey() != null && !"".equals(baseModel.getKey().trim())) {
            map.put("key", baseModel.getKey().trim());
        } else {
            map.put("key", null);
        }//查询
        PageHelper.startPage(baseModel.getPage() <= 0 ? 1 : baseModel.getPage(), baseModel.getRows() <= 0 ? 10 : baseModel.getRows());
        List<SysUserDTO> userList = userMapper.getUsers(map);
        for (SysUserDTO sysUserDTO : userList) {
            sysUserDTO.setPassword("");
        }
        PageInfo<SysUserDTO> resultUserList = new PageInfo(userList);
        baseModel.setData(resultUserList);
        return baseModel;
    }
}
